package com.zatech.cgnci.project.base.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zatech.cgnci.project.base.constant.AuthHeaderConstant;
import com.zatech.cgnci.project.base.context.UserContext;
import com.zatech.cgnci.project.base.utils.PrintUtils;
import com.zatech.cgnci.project.base.utils.VerifyUtils;
import com.zatech.cgnci.project.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author user
 */
@Component
@Slf4j
public class UserInterceptor implements InterceptorSupport {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserExcludePathConfig userExcludePathConfig;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String requestURI = req.getRequestURI();
        log.info("拦截地址：{}", requestURI);
        String token = req.getHeader(AuthHeaderConstant.auth_request_token_header);
        log.info("token：{}", token);
        if (VerifyUtils.isEmpty(token)) {
            log.info("验证失败,重新登录");
            Map<String, Object> map = new HashMap<>(16);
            map.put("code", 401);
            map.put("message", "缺失token令牌,登录鉴权失败");
            PrintUtils.print(objectMapper.writeValueAsString(map));
            return false;
        }
        UserEntity userEntity = UserEntity.USER_ENTITY_MAP.get(token);
        if (VerifyUtils.isEmpty(userEntity)) {
            log.info("验证失败,重新登录");
            Map<String, Object> map = new HashMap<>(16);
            map.put("code", 401);
            map.put("message", "缺失token令牌,登录鉴权失败");
            PrintUtils.print(objectMapper.writeValueAsString(map));
            return false;
        }
        log.info("当前用户：{}", userEntity);
        UserContext.setUser(userEntity);
        return true;
    }

    @Override
    public List<String> getExcludePathPatterns() {
        return userExcludePathConfig.getPath();
    }

    @Override
    public List<String> getPathPatterns() {
        return null;
    }

}